package com.hotau.member;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.InputFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.hotau.Executable;
import com.hotau.HotauActivity;
import com.hotau.HotauConstants;
import com.hotau.R;
import com.hotau.member.vo.User;
import com.hotau.util.DialogUtil;
import com.hotau.util.HttpRequestAsynTask;
import com.hotau.util.HttpUtil;
import com.hotau.util.ValidateUtils;

/**
 * 用户注册
 * 
 * @author Cruise
 * @data 2013-11-9
 * @version 1.0
 *          <ul>
 *          <li>1.0 创建</li>
 *          </ul>
 */
public class RegisterFragment extends Fragment implements OnClickListener {
	public static final int MOBILE_NUMBER_LENGTH = 11;

	public static final int MAX_NAME_LENGTH = 15;

	public static final int MAX_PASSWORD_LENGTH = 20;
	public static final String TAG = "RegisterFragment";

	private TextView hint = null;

	private EditText register_et_phonenum = null;

	private EditText register_et_name = null;

	private EditText register_et_password = null;

	private EditText register_et_paypassword = null;

	private CheckBox register_cb_treaty = null;

	private Button register_btn_treaty = null;

	private Button register_btn_submit = null;

	private ImageButton register_phonenum_btn_clear = null;

	private ImageButton register_name_btn_clear = null;

	private ImageButton register_password_btn_clear = null;

	private ImageButton register_paypass_btn_clear = null;

	private Handler mHandler;

	private TimerThread timerThread = null;

	/**
	 * 异步请求Task
	 */
	HttpRequestAsynTask register_task = null; // 获取找回密码校验码

	public class TimerThread extends Thread {
		private boolean stop = false;

		private int timeoutSeconds = 30;

		private Handler handler;

		public final static int TIMEOUT = 1;

		public TimerThread(int seconds, Handler handler) {
			this.timeoutSeconds = seconds;
			this.handler = handler;
		}

		public TimerThread(Handler handler) {
			this.handler = handler;
		}

		@Override
		public void run() {
			for (int i = 0; i < timeoutSeconds; i++) {
				if (stop) {
					return;
				}
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			handler.sendEmptyMessage(TIMEOUT);
		}

		public void setStop(boolean stop) {
			this.stop = stop;
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		initAllWidget();
		initAllEvent();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.member_register, container, false);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		HotauActivity csmbpActivity = (HotauActivity) getActivity();
		switch (v.getId()) {
		case R.id.member_register_btn_treaty:
			csmbpActivity.pushFragment("注册协议", new RegisterTreatyFragment());
			break;
		case R.id.member_register_btn_submit:
			if (isCheckRegister()) {
				try {
					String data = getRegisterData();
					register_task = new HttpRequestAsynTask(getActivity()) {
						HotauActivity csmbpActivity = (HotauActivity) getActivity();

						@Override
						protected void doPostExecute(String result) {
							// TODO Auto-generated method stub
							if (timerThread != null) {
								timerThread.setStop(true);
							}
							Log.d(TAG, "register_response :" + result);
							try {
								JSONObject login_result = new JSONObject(result);
								if (login_result != null
										&& login_result.getInt("result") == 1) {
									// 注册成功
									// csmbpActivity.pushFragment("信息提示",new
									// LoginActivateFragment(true));
									DialogUtil.showDialog(csmbpActivity, "",
											"您已经注册成功，激活短信将会发送至您的手机，请注意查收。",
											new Executable() {
												@Override
												public void execute() {
													csmbpActivity.toHome();
												}
											});
								} else {
									// 注册失败
									DialogUtil.showDialog(getActivity(), "",
											login_result.getString("errorMsg"));
								}
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								DialogUtil.showDialog(getActivity(), "",
										"注册返回数据出错 ");
							}
						}
					};
					register_task.execute(HotauConstants.MEMBER_REGISTER_URL,
							data, HttpUtil.UTF8_ENCODING);
					timerThread = new TimerThread(mHandler);
					Log.d(TAG, "register_request :" + data);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			break;
		case R.id.member_register_phonenum_btn_clear:
			register_et_phonenum.setText("");
			break;
		case R.id.member_register_name_btn_clear:
			register_et_name.setText("");
			break;
		case R.id.member_register_password_btn_clear:
			register_et_password.setText("");
			break;
		case R.id.member_register_paypass_btn_clear:
			register_et_paypassword.setText("");
			break;
		default:
			break;
		}
	}

	/**
	 * 初始化所有控件
	 */
	public void initAllWidget() {
		register_btn_treaty = (Button) getActivity().findViewById(
				R.id.member_register_btn_treaty);
		register_et_phonenum = (EditText) getActivity().findViewById(
				R.id.member_register_et_phonenum);
		register_et_phonenum
				.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
						MOBILE_NUMBER_LENGTH) });
		register_et_name = (EditText) getActivity().findViewById(
				R.id.member_register_et_name);
		register_et_name
				.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
						MAX_NAME_LENGTH) });
		register_et_password = (EditText) getActivity().findViewById(
				R.id.member_register_et_password);
		register_et_password
				.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
						MAX_PASSWORD_LENGTH) });
		register_et_paypassword = (EditText) getActivity().findViewById(
				R.id.member_register_et_paypassword);
		register_et_paypassword
				.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
						MAX_PASSWORD_LENGTH) });
		register_cb_treaty = (CheckBox) getActivity().findViewById(
				R.id.member_register_cb_treaty);
		register_btn_submit = (Button) getActivity().findViewById(
				R.id.member_register_btn_submit);

		register_phonenum_btn_clear = (ImageButton) getActivity().findViewById(
				R.id.member_register_phonenum_btn_clear);
		register_name_btn_clear = (ImageButton) getActivity().findViewById(
				R.id.member_register_name_btn_clear);
		register_password_btn_clear = (ImageButton) getActivity().findViewById(
				R.id.member_register_password_btn_clear);
		register_paypass_btn_clear = (ImageButton) getActivity().findViewById(
				R.id.member_register_paypass_btn_clear);
		hint = (TextView) getActivity().findViewById(R.id.register_hint);

		register_cb_treaty
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						// TODO Auto-generated method stub
						if (isChecked) {
							hint.setVisibility(View.INVISIBLE);
						} else {
							hint.setVisibility(View.VISIBLE);
						}
					}
				});
		register_cb_treaty.setChecked(false);
	}

	/**
	 * 初始化所有事件
	 */
	public void initAllEvent() {
		register_btn_treaty.setOnClickListener(this);
		register_btn_submit.setOnClickListener(this);

		register_phonenum_btn_clear.setOnClickListener(this);
		register_name_btn_clear.setOnClickListener(this);
		register_password_btn_clear.setOnClickListener(this);
		register_paypass_btn_clear.setOnClickListener(this);

		mHandler = new Handler() {
			public void handleMessage(android.os.Message msg) {
				if (msg.what == TimerThread.TIMEOUT) {
					DialogUtil.showDialog(getActivity(), "",
							"注册异常，请检查网络并且联系服务商");
				}
			};
		};

	}

	/**
	 * 注册前进行检查
	 * 
	 * @return
	 */
	public boolean isCheckRegister() {
		if (!User.isMobileNO(register_et_phonenum.getText().toString())) {
			DialogUtil.showDialog(getActivity(), "", "请输入正确的手机号码");
			return false;
		}
		if ("".equals(register_et_name.getText().toString().trim())
				|| register_et_name.getText().toString().length() > 15) {
			DialogUtil.showDialog(getActivity(), "", "真实姓名不能为空或长度超过15个字");
			return false;
		}

		if (ValidateUtils.empty(register_et_password.getText().toString())) {
			DialogUtil.showDialog(getActivity(), "", "登陆密码不能为空！");
			return false;
		}

		if (register_et_password.getText().length() < 8
				|| register_et_password.getText().length() > 20) {
			DialogUtil.showDialog(getActivity(), "", "登陆密码必须要8~20个字符!");
			return false;
		}

		if (ValidateUtils.empty(register_et_paypassword.getText().toString())) {
			DialogUtil.showDialog(getActivity(), "", "支付密码不能为空！");
			return false;
		}

		if (!ValidateUtils.isLetteric(register_et_paypassword.getText()
				.toString().trim().substring(0, 1))) {
			DialogUtil.showDialog(getActivity(), "", "支付密码第一位必须为字母");
			return false;
		}
		if (!ValidateUtils.isNumberLetteric(register_et_paypassword.getText()
				.toString().trim())) {
			DialogUtil.showDialog(getActivity(), "", "支付密码必须为字母和（或）数字的组合");
			return false;
		}

		if (register_et_paypassword.getText().length() < 8
				|| register_et_paypassword.getText().length() > 20) {
			DialogUtil.showDialog(getActivity(), "", "支付密码长度过短");
			return false;
		}
		if (!register_cb_treaty.isChecked()) {
			DialogUtil.showDialog(getActivity(), "", "必须同意注册协议");
			return false;
		}

		return true;
	}

	/**
	 * 注册数据
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getRegisterData() throws Exception {
		if (!isCheckRegister()) {
			throw new Exception();
		}
		StringBuilder sb_register = new StringBuilder();
		sb_register.append("Form:userCode=" + register_et_phonenum.getText());
		sb_register.append(";loginPwd=" + register_et_password.getText());
		sb_register.append(";payPwd=" + register_et_paypassword.getText());
		sb_register.append(";realName=" + register_et_name.getText());
		sb_register.append(";terminalCode="
				+ HotauConstants.getTerminalCode(getActivity()));
		return sb_register.toString();
	}

}
